package com.lyl.goods.controller;

import com.lyl.goods.pojo.Product;
import com.lyl.goods.pojo.ShoppingCart;
import com.lyl.goods.respository.CartRepository;
import com.lyl.goods.respository.ProductRepository;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;


/**
 * @Author: Liyunlong
 * @Date: 2024/03/01/19:08
 * @Description:
 */
@Controller
@Slf4j
public class CartController {

    @Autowired
    private CartRepository cartRepository;

    @Resource
    private ProductRepository productRepository;

    /**
     * @Description: 根据用户id展示购物车
     * @Author: Liyunlong
     * @Date: 2024/3/2
     */
    @GetMapping("/cartList")
    public String showCartForm(HttpSession session, Model model) {

        String currentUser = (String) session.getAttribute("currentUser");
        model.addAttribute("userName", currentUser);
//
        Integer userId = (Integer) session.getAttribute("userId");
        List<ShoppingCart> shoppingCart = cartRepository.getByUserId(userId);
        // 创建一个列表，存储购物车每一项的信息，包括商品名、价格、数量及总价
        List<Map<String, Object>> cartItemList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCart) {
            Integer productId = cart.getProductId();
            List<Product> productList = productRepository.getById(productId);
            if (!productList.isEmpty()) {
                Product product = productList.get(0);
                Map<String, Object> cartItemInfo = new HashMap<>();
                cartItemInfo.put("cartId", cart.getCartId());
                cartItemInfo.put("productName", product.getName());
                cartItemInfo.put("productPrice", product.getPrice());
                cartItemInfo.put("quantity", cart.getQuantity());
                // 计算总价
                cartItemInfo.put("totalPrice", product.getPrice().multiply(BigDecimal.valueOf(cart.getQuantity())));
                cartItemList.add(cartItemInfo);
            }
        }
        log.info("展示用户：{}的购物车信息", userId);
        model.addAttribute("cartItemList", cartItemList);
        return "cartList";
    }

    /**
     * @Description: 加入购物车
     * @Author: Liyunlong
     * @Date: 2024/3/2
     */

    @RequestMapping("/addCart")
    public String addCart(@RequestParam("id") Long productId, HttpSession session) {
        log.info("商品的ID:{}", productId);
        ShoppingCart shoppingCart = cartRepository.getByProductId(Math.toIntExact(productId));
        if (shoppingCart != null && shoppingCart.getCartId() != null) {
            ShoppingCart shoppingCart1 = new ShoppingCart();
            shoppingCart1.setQuantity(shoppingCart.getQuantity() + 1);
            shoppingCart1.setCartId(shoppingCart.getCartId());
            shoppingCart1.setProductId(Math.toIntExact(productId));
            Integer userId = (Integer) session.getAttribute("userId");
            shoppingCart1.setAddedTime(LocalDateTime.now());
            shoppingCart1.setUserId(userId);
            cartRepository.save(shoppingCart1);
            log.info("购物车已经存在该商品，再次点击添加购物车，数量直接加1");
        } else {
            // 如果购物车中不存在该商品，则添加新记录
            ShoppingCart shoppingCart2 = new ShoppingCart();
            shoppingCart2.setQuantity(1);
            shoppingCart2.setProductId(Math.toIntExact(productId));
            shoppingCart2.setAddedTime(LocalDateTime.now());
            Integer userId = (Integer) session.getAttribute("userId");
            shoppingCart2.setUserId(userId);
            cartRepository.save(shoppingCart2);
            log.info("新增一条商品到购物车，商品ID为：{}", shoppingCart2.getProductId());
        }
        return "redirect:/cartList";
    }

    /**
     * @Description: 删除购物车
     * @Author: Liyunlong
     * @Date: 2024/3/2
     */
    @RequestMapping("/cart/deleteProduct")
    public String delete(@RequestParam("cartId") Long cartId) {
        log.info("删除购物车中的商品：{}", cartId);
        cartRepository.deleteById(cartId);
        log.info("删除购物车中的商品，商品Id:{}", cartId);
        return "redirect:/cartList";
    }

    /**
     * @Description: 购物车商品+1
     * @Author: Liyunlong
     * @Date: 2024/3/2
     */
    @RequestMapping("/JiaProduct")
    public String addQuautity(@RequestParam("cartId") Long cartId, HttpSession session) {
        ShoppingCart shoppingCart = getShoppingCart(cartId);
        int quantity = shoppingCart.getQuantity();
        quantity = quantity + 1;
        ShoppingCart shoppingCart1 = new ShoppingCart();
        shoppingCart1.setQuantity(quantity);
        shoppingCart1.setProductId(shoppingCart.getProductId());
        shoppingCart1.setCartId(Math.toIntExact(cartId));
        Integer userId = (Integer) session.getAttribute("userId");
        shoppingCart1.setUserId(userId);
        shoppingCart1.setAddedTime(LocalDateTime.now());
        cartRepository.save(shoppingCart1);
        log.info("购物车商品喜加一");
        return "redirect:/cartList";
    }

    @NotNull
    private ShoppingCart getShoppingCart(Long cartId) {
        ShoppingCart shoppingCart = cartRepository.getById(cartId);
        return shoppingCart;
    }

    /**
     * @Description: 商品-1
     * @Author: Liyunlong
     * @Date: 2024/3/2
     */
    @RequestMapping("/JianProduct")
    public String JianQuautity(@RequestParam("cartId") Long cartId, HttpSession session) {
        ShoppingCart shoppingCart = getShoppingCart(cartId);
        int quantity = shoppingCart.getQuantity();
        ShoppingCart shoppingCart1 = new ShoppingCart();
        if (quantity > 0) {
            quantity -= 1;
            shoppingCart1.setCartId(Math.toIntExact(cartId));
            shoppingCart1.setProductId(shoppingCart.getProductId());
            shoppingCart1.setQuantity(quantity);
            Integer userId = (Integer) session.getAttribute("userId");
            shoppingCart1.setUserId(userId);
            shoppingCart1.setAddedTime(LocalDateTime.now());
            cartRepository.save(shoppingCart1);
            log.info("购物车商品喜减一");
        }
        if (quantity == 0) {
            cartRepository.deleteById(cartId);
            log.info("购物车商品减为0，即将从该购物车中移除商品");
        }
        return "redirect:/cartList";
    }
}
